package dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.iterators.EntrySetMapIterator;

import util.Util;

import model.LoaiBenh;
import dao.LoaiBenhDAO;

public class LoaiBenhDAOHibernate extends GenericHibernateDAO<LoaiBenh, Long>
		implements LoaiBenhDAO {
	@SuppressWarnings("unchecked")
	@Override
	public List<LoaiBenh> findByIdLoaiBenhLike(String keyword) {
		return getSession()
				.createQuery(
						"FROM LoaiBenh AS loaiBenh WHERE loaiBenh.tenLoaiBenh LIKE :pname")
				.setString("pname", "%" + keyword + "%").list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LoaiBenh> findByChuyenKhoaLike(String keyword) {
		return getSession()
				.createQuery(
						"SELECT loaiBenh FROM LoaiBenh AS loaiBenh JOIN loaiBenh.chuyenKhoa AS chuyenKhoa WHERE chuyenKhoa.tenChuyenKhoa LIKE :pname")
				.setString("pname", "%" + keyword + "%").list();
	}

	@Override
	public List<LoaiBenh> findByOneCondition(String criteria, String keyWord) {
		List<LoaiBenh> result = new ArrayList<LoaiBenh>();
		if (criteria.equals("tenLoaiBenh")) {
			result = findByIdLoaiBenhLike(keyWord);
		} else if (criteria.equals("tenChuyenKhoa")) {
			result = findByChuyenKhoaLike(keyWord);
		}
		return result;
	}

	@Override
	public List<LoaiBenh> findByKeyword(String keyword) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LoaiBenh> findByTenLoaiBenh(String name) {
		return getSession()
				.createQuery(
						"FROM LoaiBenh AS loaiBenh WHERE loaiBenh.tenLoaiBenh LIKE :pname")
				.setString("pname", "%" + name + "%").list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LoaiBenh> findByManyConditions(MultiMap conditions) {
		List<LoaiBenh> result = null;
		EntrySetMapIterator iterator = new EntrySetMapIterator(conditions);
		String criteria = "";
		List<String> keywords = new ArrayList<String>();
		String keyword = "";
		while (iterator.hasNext()) {
			criteria = (String) iterator.next();
			keywords = (ArrayList<String>) conditions.get(criteria);
			for (String k : keywords) {
				keyword = k;
				if (criteria.equals("tenLoaiBenh")) {
					List<LoaiBenh> list = findByTenLoaiBenh(keyword);
					result = Util.retainAllLoaiBenh(result, list);
				}
			}
		}
		return result;
	}

}
